package cn.xzzz2020.XJynWeb.mvc.render.impl;

import cn.xzzz2020.XJynWeb.mvc.RequestProcessorChain;
import cn.xzzz2020.XJynWeb.mvc.render.ResultRender;
import com.google.gson.Gson;

import java.io.PrintWriter;

/**
 * 将结果返回成Json数据
 * @author xzzz2020
 * @version 1.0
 * @date 2020/9/4 16:29
 */
public class JsonResultRender implements ResultRender {
    private Object jsonData;
    public JsonResultRender(Object jsonData) {
        this.jsonData = jsonData;
    }

    @Override
    public void render(RequestProcessorChain requestProcessorChain) throws Exception {
        //设置响应头
        requestProcessorChain.getResponse().setContentType("application/json");
        requestProcessorChain.getResponse().setCharacterEncoding("UTF-8");
        //响应流写入经过Gson格式化的处理结果
        PrintWriter writer = requestProcessorChain.getResponse().getWriter();
        Gson gson = new Gson();
        String str = gson.toJson(jsonData);
        writer.write(str);
        writer.flush();
    }
}
